mui.init({});
var userinfo = app.getState() || {};
var uid = userinfo.user_id;
var currentPage1 = 1;
var currentPage2 = 1;
var pageSize = 10;
var total_page1 = 0;
var total_count1 = 0;
var total_page2 = 0;
var total_count2 = 0;

window.onload = function() {}

//阻尼系数
var deceleration = mui.os.ios ? 0.003 : 0.0009;
mui('.mui-scroll-wrapper').scroll({
	bounce: false,
	indicators: true, //是否显示滚动条
	deceleration: deceleration
});

mui.plusReady(function() {
	//关闭等待框
	plus.nativeUI.closeWaiting();
	//显示当前页面
	mui.currentWebview.show();

	refresh_data();

	window.addEventListener('refresh_data', function(event) {
		refresh_data();
	});

});

function refresh_data() {
	userinfo = app.getState() || {};
	uid = userinfo.user_id;
	mui.ajax({
		url: apiurl + "Trade/sale_unfinished_trade/",
		data: {
			'p': 1,
			'size': pageSize,
			'user_id': uid,
			'_token': userinfo.token
		},
		async: true,
		dataType: 'json',
		crossDomain: true, //强制使用5+跨域
		type: 'get',
		timeout: 10000,
		success: function(res) {
			console.log(JSON.stringify(res));
			if(res.status == -3) {
				mui.toast(res.msg);
				app.out();
				return false;
			}

			// 请求成功
			if(!res.status) {
				mui.toast('未获取到数据');
			} else {

				$('#item1mobile ul').empty();
				$('#item2mobile ul').empty();

				var data_1 = assemble_data(res.resource1);
				$('#item1mobile ul').append(data_1);
				total_page1 = res.total_page1;
				total_count1 = res.sum1;

				var data_2 = assemble_data(res.resource2);
				$('#item2mobile ul').append(data_2);
				total_page2 = res.total_page2;
				total_count2 = res.sum2;

			}
		},
		error: function(xhr, type, errorThrown) {
			//console.log(JSON.stringify(xhr));
			//console.log(JSON.stringify(type));
			//console.log(JSON.stringify(errorThrown));
			mui.toast('获取数据失败！');
		}
	});

	//循环初始化所有下拉刷新，上拉加载。
	mui.each(document.querySelectorAll('.mui-slider-group .mui-scroll'), function(index, pullRefreshEl) {
		mui(pullRefreshEl).pullToRefresh({
			up: {
				callback: function() {
					var self = this;
					setTimeout(function() {
						if(index == 0) {
							currentPage1++;

							mui.ajax({
								url: apiurl + "Trade/sale_unfinished_trade/",
								data: {
									'p': currentPage1,
									'size': pageSize,
									'user_id': uid,
									'type': 1,
									'_token': userinfo.token
								},
								async: true,
								dataType: 'json',
								crossDomain: true, //强制使用5+跨域
								type: 'get',
								timeout: 10000,
								success: function(res) {
									console.log(JSON.stringify(res));
									if(res.status == -3) {
										mui.toast(res.msg);
										app.out();
										return false;
									}

									// 请求成功
									if(!res.status) {
										mui.toast('未获取到数据');
									} else {
										var data_1 = assemble_data(res.resource);
										$('#item1mobile ul').append(data_1);

										if(currentPage1 < total_page1) {
											self.endPullUpToRefresh(false); /*能上拉*/
										} else {
											self.endPullUpToRefresh(true); /*不能上拉*/
										}
									}
								},
								error: function(xhr, type, errorThrown) {
									//console.log(JSON.stringify(xhr));
									//console.log(JSON.stringify(type));
									//console.log(JSON.stringify(errorThrown));
									mui.toast('获取数据失败！');
								}
							});
							return;
						}

						if(index == 1) {
							currentPage2++;
							/*
											 if(currentPage2>total_page2 || total_count2<=$('#item2mobile ul li').length){
													self.endPullUpToRefresh(true);//参数为true代表没有更多数据了。
													return false;
											}*/
							mui.ajax({
								url: apiurl + "Trade/sale_unfinished_trade/",
								data: {
									'p': currentPage2,
									'size': pageSize,
									'user_id': uid,
									'type': 2,
									'_token': userinfo.token
								},
								async: true,
								dataType: 'json',
								crossDomain: true, //强制使用5+跨域
								type: 'get',
								timeout: 10000,
								success: function(res) {
									console.log(JSON.stringify(res));
									if(res.status == -3) {
										mui.toast(res.msg);
										app.out();
										return false;
									}

									// 请求成功
									if(!res.status) {
										mui.toast('未获取到数据');
									} else {
										var data_2 = assemble_data(res.resource);
										$('#item2mobile ul').append(data_2);

										if(currentPage2 < total_page2) {
											self.endPullUpToRefresh(false); /*能上拉*/
										} else {
											self.endPullUpToRefresh(true); /*不能上拉*/
										}
									}
								},
								error: function(xhr, type, errorThrown) {
									//console.log(JSON.stringify(xhr));
									//console.log(JSON.stringify(type));
									//console.log(JSON.stringify(errorThrown));
									mui.toast('获取数据失败！');
								}
							});
							return;
						}

					}, 1500);
				}
			}
		});
	});
}

function assemble_data(data) {
	/*
    	 * <li class="mui-table-view-cell">
										<div class="ordertop">
											<div class="otitle">
												<span class="buy" style="float:left;line-height:30px;">买入</span>
							                    <span class="sell" style="float:left;line-height:30px;">打款</span>
												<span>2018-02-02 15:15:15</span>
											</div>
											<div class="omain">
												<p>订单号：15615681995</p>
												<p>收款人:某某某<span>1000</span></p>
												<p style="color: #333;">订单创建中<span>实际应付999</span></p>
											</div>
										</div>
									</li>
    	 */
	var htm = '';
	for(z in data) {
		htm += '<li class="mui-table-view-cell">';
		htm += '<div class="ordertop">';
		htm += '<div class="otitle">';
		htm += '<span class="buy" style="float:left;line-height:30px;">卖出</span>';
		if(data[z]['status'] == 3) {
			htm += '<span class="sell receipt" onclick="do_receipt(\'' + data[z]['id'] + '\')" style="float:left;line-height:30px;margin-left:3%;">收款</span>';
		}
		if(data[z]['status'] == 1) {
			htm += '<span class="sell receipt" onclick="do_cencel(\'' + data[z]['id'] + '\')" style="float:left;line-height:30px;margin-left:3%;">取消</span>';
		}

		htm += '<span>' + data[z]['add_time'] + '</span>';
		htm += '</div>';
		htm += '<div class="omain" onclick="see_detail(\'' + data[z]['id'] + '\')" >';
		htm += '<p>订单号：' + data[z]['order_sn'] + '</p>';
		if(data[z]['status'] == 1) {
			htm += '<p>还未匹配买方<span>' + data[z]['trade_money'] + '</span></p>';
		} else {
			htm += '<p>打款人:' + data[z]['buy_contacts'] + '<span>' + data[z]['trade_money'] + '</span></p>';
		}
		htm += '<p>订单创建中<span>实际应付金额' + data[z]['amount'] + ' RMB</span></p>';
		htm += '</div>';
		htm += '</div>';
		htm += '</li>';
	}
	return htm;
}

//看订单详情
function see_detail(tid) {
	//打开卖出订单详情
	mui.openWindow({
		id: 'buyorder.html',
		url: 'buyorder.html',
		extras: {
			trade_id: tid //自定义扩展参数，可以用来处理页面间传值
		},
		show: {
			autoShow: false
		},
		waiting: {
			autoShow: true,
			title: '正在加载...'
		}
	});
}

//收款页
function do_receipt(tid) {
	//打开打款详情
	mui.openWindow({
		id: 'receipt_detail.html',
		url: 'receipt_detail.html',
		extras: {
			trade_id: tid //自定义扩展参数，可以用来处理页面间传值
		},
		show: {
			autoShow: false
		},
		waiting: {
			autoShow: true,
			title: '正在加载...'
		}
	});
}

//取消
function do_cencel(tid) {
	mui.ajax({
		url: apiurl + "Trade/updateTrade/",
		data: {
			'user_id': userinfo.user_id,
			'tid': tid,
			'type': 3,
			'_token': userinfo.token
		},
		async: true,
		dataType: 'json',
		crossDomain: true, //强制使用5+跨域
		type: 'post',
		timeout: 10000,
		success: function(res) {
			console.log(JSON.stringify(res));
			if(res.status == -3) {
				mui.toast(res.msg);
				app.out();
				return false;
			}

			// 请求成功
			if(res.result < 1) {
				mui.alert(res.msg);
			} else {
				mui.toast('取消成功');
				userinfo.a1_money = res.data.a1_money;
				userinfo.a2_money = res.data.a2_money;
				app.setState(userinfo);
				mui.fire(plus.webview.getWebviewById('index.html'), 'refresh_amoney');
				refresh_data();
			}
		},
		error: function(xhr, type, errorThrown) {
			//console.log(JSON.stringify(xhr));
			//console.log(JSON.stringify(type));					//console.log(JSON.stringify(errorThrown));
			mui.toast('操作失败！');
		}
	});
}